package com.rabbiter.controller;


import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbiter.common.QueryPageParam;
import com.rabbiter.common.Result;
import com.rabbiter.config.SecurityConfig;
import com.rabbiter.entity.Menu;
import com.rabbiter.entity.User;
import com.rabbiter.service.MenuService;
import com.rabbiter.service.UserService;
import com.rabbiter.util.MinioUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器：用户管理和管理员管理模块
 * </p>
 *
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;

    @Resource
    private SecurityConfig securityConfig;


    /*
     * 查询全部用户
     */
    @GetMapping("/list")
    public List<User> list(){
        return userService.list();
    }

    /*
     根据账号查找用户
     */
    @GetMapping("/findByNo")
    public Result findByNo(@RequestParam String no){
        List list = userService.lambdaQuery().eq(User::getNo,no).list(); //返回userservice，
        return list.size()>0?Result.success(list):Result.fail();
    }


    //新增用户
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        //保存、以及保存的对象是User
        try {
            //判断账号是否存在
            User userNo = userService.lambdaQuery().eq(User::getNo, user.getNo()).one();
            if (userNo != null) {
                return Result.fail("账号已存在");
            }
            //加密密码
            String password = user.getPassword();
            String encrypt = securityConfig.encrypt(password);
            user.setPassword(encrypt);
            userService.saveAll(user);
            return Result.success("成功插入用户");
        } catch (Exception e) {
            return Result.fail("出错了");
        }
    }


    //更新头像
    @RequestMapping("/updateAvatar/{id}")
    public Result updateAvatar(@PathVariable("id") Integer id,
                               @RequestParam("file") MultipartFile file) throws Exception {
        System.out.println("file=="+file.getOriginalFilename());
        String Url = userService.updateAvatar(id,file);
        return Result.success(Url);
    }

    //更新用户
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        return userService.updateById(user)?Result.success():Result.fail();
    }

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) throws NoSuchAlgorithmException {
        // 检查传入的user对象是否为null
        if (user == null) {
            return Result.fail("请求体为空");
        }

        // 匹配账号
        User loggedInUser = userService.lambdaQuery()
                .eq(User::getNo, user.getNo())
                .one();
        if (loggedInUser == null) {
            return Result.fail("账号不存在");
        }
        // 匹配加密后的密码
        boolean decrypt = securityConfig.decrypt(user.getPassword(), loggedInUser.getPassword());
        if (!decrypt) {
            return Result.fail("密码错误");
        } else  {
            // 登录成功，设置token
            StpUtil.login(loggedInUser.getNo());//以唯一标识作为登录凭证

            SaSession tokenSession = StpUtil.getTokenSession();//返回前端的token
            System.out.println(tokenSession);
            List<Menu> menuList = menuService.lambdaQuery()
                .like(Menu::getMenuright, loggedInUser.getRoleId().toString())
                .list();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("user", loggedInUser);
            resultMap.put("menu", menuList);
            resultMap.put("token", tokenSession);//token信息
            return Result.success(resultMap);
        }
    }


    /*
     * 删除用户
     */
    @GetMapping("/del")
    public Result delete(Integer id){
        StpUtil.logout();
        return userService.removeById(id)?Result.success():Result.fail();
    }

    /*
     * 模糊查询
     */
    @PostMapping("/listP")
    public Result query(@RequestBody User user){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(user.getName())){
            wrapper.like(User::getName,user.getName()); //like的模糊查询
        }
        return Result.success(userService.list(wrapper));
    }

    /*
     * 分页查询
     */
    @PostMapping("/listPage")
    public List<User> listPage(@RequestBody QueryPageParam query){ //封装了参数QueryPageParam query
        HashMap param = query.getParam(); //param是参数，把所有的要传进来的都往里放
        String name = (String)param.get("name");
        System.out.println("name=>"+(String)param.get("name")); //通过接口把数据传过来

        Page<User> page = new Page(); //用分页拦截器分页，page对象
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName,name);

        IPage result = userService.page(page,lambdaQueryWrapper); //对模糊查询姓名后的结果分页处理

        System.out.println("total=>"+result.getTotal()); //打印总记录数

        return result.getRecords(); //返回结果
    }
    //概括一下：先定义page，再查询数据库数据，然后用自带的函数进行分页处理


    /*
     * 查询功能：根据前端表单输入的信息或者下拉框选择查询用户，并以分页的形式返回前端。（自定义）
     */
    @PostMapping("/listPageC1")
    public Result listPageC1(@RequestBody QueryPageParam query){
        HashMap param = query.getParam();
        String name = (String)param.get("name");
        String sex = String.valueOf(param.get("sex"));
        String roleId = (String)param.get("roleId");
        String avatar = (String) param.get("avatar");

        Page<User> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>(); //使用wrapper自定义SQL
        if(StringUtils.isNotBlank(name) && !"null".equals(name)){
            lambdaQueryWrapper.like(User::getName,name);
        }
        if(StringUtils.isNotBlank(sex)){
            lambdaQueryWrapper.eq(User::getSex,sex);
        }
        if(StringUtils.isNotBlank(roleId)){
            lambdaQueryWrapper.eq(User::getRoleId,roleId);
        }

        IPage result = userService.pageCC(page,lambdaQueryWrapper);

        System.out.println("total=>"+result.getTotal());

        ArrayList<Object> list = new ArrayList<>();
        list.add(result.getRecords());
        list.add(result.getTotal());
        return Result.success(list);
    }

}
